#include "app_uart1.h"
#include "bsp_rs485.h"
#include "bsp_uart6.h"
#include "usart.h"

void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size)
{
	uart1_rx_frame_t frame;
	rs485_rx_frame_t rs485_frame;
    uart6_frame_t uart6_frame;

	if (huart == &huart1 && huart->RxEventType == HAL_UART_RXEVENT_IDLE)
	{
		frame.start = uart1_rx_cb.tail;
		frame.end = uart1_rx_cb.tail + Size - 1;

		uart1_rx_frame_enqueue(&frame);

		uart1_rx_cb.tail += Size;
		if (UART1_RX_BUF_SIZE - uart1_rx_cb.tail + 1 < UART1_RX_MAX_SIZE)
		{
			uart1_rx_cb.tail = 0;
		}

		HAL_UARTEx_ReceiveToIdle_DMA(&huart1, &uart1_rx_cb.buf[uart1_rx_cb.tail],
									 UART1_RX_MAX_SIZE + 1);
	}

    if (huart == &huart2 && huart->RxEventType == HAL_UART_RXEVENT_IDLE)
	{
        rs485_frame.start = rs485_rx_cb.tail;
        rs485_frame.end = rs485_rx_cb.tail + Size - 1;

        rs485_rx_frame_enqueue(&rs485_frame);

        rs485_rx_cb.tail += Size;
        if (RS485_RX_BUF_SIZE - rs485_rx_cb.tail + 1 < RS485_RX_MAX_SIZE)
        {
            rs485_rx_cb.tail = 0;
        }

        HAL_UARTEx_ReceiveToIdle_DMA(&huart2, &rs485_rx_cb.buf[rs485_rx_cb.tail],
									 RS485_RX_MAX_SIZE + 1);
	}

    if (huart == &huart6 && huart->RxEventType == HAL_UART_RXEVENT_IDLE)
    {
        uart6_frame.start = uart6_rx_cb.tail;
        uart6_frame.end = uart6_rx_cb.tail + Size - 1;

        uart6_rx_frame_enqueue(&uart6_frame);

        uart6_rx_cb.tail += Size;
        if (UART6_BUF_SIZE - uart6_rx_cb.tail + 1 < UART6_MAX_SIZE)
        {
            uart6_rx_cb.tail = 0;
        }

        HAL_UARTEx_ReceiveToIdle_DMA(&huart6, &uart6_rx_cb.buf[uart6_rx_cb.tail],
									 UART6_MAX_SIZE + 1);
    }
}

void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)
{
    if (huart == &huart6)
    {
        uart6_tx_frame_queue.status = 1;
    }
}
